package com.eric.windows.util;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.widget.ImageView;

import com.nostra13.universalimageloader.cache.disc.DiskCache;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import java.io.File;

/**
 * <h3>Description</h3> ImageLoader图片下载工具类
 * TODO
 * <h3>Author</h3> luzhenbang
 * <h3>Date</h3> 2016/1/13 10:29
 * <h3>Copyright</h3> Copyright (c)2016 Shenzhen Tentinet Technology Co., Ltd. Inc. All rights reserved.
 */
public class ImageLoaderUtil  {

    /**
     * 初始化imageLoader
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2016/1/13,10:36
     * <h3>UpdateTime</h3> 2016/1/13,10:36
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     *
     * @param context 上下文
     */
    public static void initImageLoader(Context context ){
        //FileUtil.getAppCacheAbsoluteFile(context) 用来创建缓存文件
        DiskCache cache = new UnlimitedDiskCache(getAppCacheAbsoluteFile(context));
        //ImageUtil.PATH_USER_IMAGE为文件路径
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .memoryCacheExtraOptions(480, 800) // max width, max height，即保存的每个缓存文件的最大长宽
                .threadPoolSize(3) //线程池内线程的数量
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator()) //将保存的时候的URI名称用MD5 加密
                .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024))
                .memoryCacheSize(2 * 1024 * 1024) // 内存缓存的最大值
                .diskCacheSize(50 * 1024 * 1024)  // SD卡缓存的最大值
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                        // 由原先的discCache -> diskCache
                .diskCache(cache)//自定义缓存路径
                .imageDownloader(new BaseImageDownloader(context, 5 * 1000, 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超时时间
                .writeDebugLogs() // Remove for release app
                .build();
        //全局初始化此配置
        ImageLoader.getInstance().init(config);
    }

    /**
     * 设置显示配置
     *
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2016/1/13,10:45
     * <h3>UpdateTime</h3> 2016/1/13,10:45
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     *
     * @param resFailId 加载失败显示图片的id
     * @param resLoadingId 加载的过程显示图片的id
     * @return
     */
    public static DisplayImageOptions getDisplayImageOptions(int resFailId, int resLoadingId) {
        DisplayImageOptions.Builder builder = new DisplayImageOptions.Builder();
        //启用内存缓存
        builder.cacheInMemory(true);
        builder.cacheOnDisk(true);
        builder.showImageOnLoading(resLoadingId);
        builder.showImageOnFail(resFailId);
        return builder.build();
    }


    /**
     * 从内存卡中异步加载本地图片
     *
     * @param uri 图片的绝对路径
     * @param imageView 需要显示图片的ImageView对象
     * @param options 显示配置
     */
    public  void displayFromSDCard(String uri, ImageView imageView , DisplayImageOptions options ) {
        ImageLoader.getInstance().displayImage("file://" + uri, imageView, options);
    }


    /**
     *
     * 从网络上下载图片
     *
     * @version 1.0
     * @createTime 2015-12-30,上午11:39:58
     * @updateTime 2015-12-30,上午11:39:58
     * @createAuthor lzb
     * @updateAuthor
     * @updateInfo (此处输入修改内容,若无修改可不写.)
     * @param uri 网络地址
     * @param imageView 需要显示图片的ImageView对象
     * @param options 显示配置
     */
    public  void displayFromNet(String uri, ImageView imageView , DisplayImageOptions options ) {
        ImageLoader.getInstance().displayImage(uri, imageView, options);
    }

    /**
     * 从assets文件夹中异步加载图片
     *
     * @param imageName
     *            图片名称，带后缀的，例如：1.png
     * @param imageView
     */
    public void dispalyFromAssets(String imageName, ImageView imageView ,DisplayImageOptions options) {
        // String imageUri = "assets://image.png"; // from assets
        ImageLoader.getInstance().displayImage("assets://" + imageName, imageView ,options);
    }

    /**
     * 从drawable中异步加载本地图片
     *
     * @param imageId
     * @param imageView
     */
    public void displayFromDrawable(int imageId, ImageView imageView ,DisplayImageOptions options) {
        // String imageUri = "drawable://" + R.drawable.image; // from drawables
        // (only images, non-9patch)
        ImageLoader.getInstance().displayImage("drawable://" + imageId, imageView, options);
    }

    /**
     * 从内容提提供者中抓取图片
     */
    public void displayFromContent(String uri, ImageView imageView,DisplayImageOptions options) {
        ImageLoader.getInstance().displayImage("content://" + uri, imageView, options);
    }


    public static File getAppCacheAbsoluteFile(Context context){
        String appPath = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            appPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + getAppName(context) + File.separator;
        }else {
            appPath = Environment.getDataDirectory().getAbsolutePath() + File.separator + getPackageName(context) + File.separator;
        }
        File file = new File(appPath);
        if (!file.exists()){
            file.mkdirs();
        }
        return file;
    }

    public static String getAppName(Context context) {
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
            packageManager = context.getApplicationContext().getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            applicationInfo = null;
        }
        String applicationName = (String) packageManager.getApplicationLabel(applicationInfo);
        return applicationName;
    }

    public static String getPackageName(Context context){
        String packageString = context.getPackageName();
        return packageString;
    }

}
